package com.wzcl.app.service.impl;

import com.wzcl.app.dao.model.ActivityRule;
import com.wzcl.app.dao.model.ActivityRuleInfo;
import com.wzcl.app.dao.repository.ActivityRuleInfoRepository;
import com.wzcl.app.model.dto.ActivityRuleInfoDto;
import com.wzcl.app.service.ActivityRuleInfoService;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Log4j2
@Service
public class ActivityRuleInfoServiceImpl implements ActivityRuleInfoService {

    @Autowired
    private ActivityRuleInfoRepository ruleInfoRepository;

    @Override
    public void addRuleInfoByRule(ActivityRule activityRule, List<ActivityRuleInfoDto> activityRuleInfoDtoList) {
        List<ActivityRuleInfo> list = activityRuleInfoDtoList.stream().map(activityRuleInfoDto -> {
            ActivityRuleInfo ruleInfo = new ActivityRuleInfo();
            BeanUtils.copyProperties(activityRuleInfoDto, ruleInfo, "id");
            ruleInfo.setActivityRule(activityRule);
            return ruleInfo;
        }).collect(Collectors.toList());
        ruleInfoRepository.saveAll(list);
    }

    @Override
    public void updateRuleInfoByRule(ActivityRule activityRule, List<ActivityRuleInfoDto> ruleInfoDtoList) {
        //删除原有的 之后全新增
        delRuleInfoByRule(activityRule);
        addRuleInfoByRule(activityRule, ruleInfoDtoList);
    }

    @Override
    public void delRuleInfoByRule(ActivityRule activityRule) {
        //删除原有的 之后全新增
        List<ActivityRuleInfo> oldRuleInfo = ruleInfoRepository.findAllByActivityRule_Id(activityRule.getId());
        if (oldRuleInfo != null && oldRuleInfo.size() > 0) {
            ruleInfoRepository.deleteAll(oldRuleInfo);
        }
    }
}
